package com.primaryedu.ui.app.leave;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.LeavephotoBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.CustomDialog;
import com.primaryedu.dialog.PhotosDialog;
import com.primaryedu.photo.PhotoPickerActivity;
import com.primaryedu.photo.PhotoPickerIntent;
import com.primaryedu.photo.PhotoPreviewActivity;
import com.primaryedu.photo.PhotoPreviewIntent;
import com.primaryedu.photo.SelectModel;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.ImageUtil;
import com.primaryedu.utils.Logger;
import com.primaryedu.utils.UploadUtil;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.CustomDatePicker;
import com.primaryedu.widget.MyGridView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;

/**
 * 应用中心---请假
 *
 * @author jun.wang
 * @description
 * @data 2018年1月4日
 */
public class LeaveActivity extends BaseActivity implements OnClickListener, UploadUtil.OnUploadProcessListener {
    private String TAG = LeaveActivity.class.getSimpleName();
    private CustomDatePicker customDatePicker_startime;
    private CustomDatePicker customDatePicker_endtime;
    private TextView tv_starttime;
    private TextView tv_endtime;
    private CustomDialog.Builder ibuilder;
    private String now;
    private RadioGroup rg_leave;
    private int typeLeave;
    private EditText et_reason;
    private MyGridView gridView;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private GridLeaveAdapter gridAdapter;
    private PhotosDialog.Builder Builder;
    private String picpath1 = "";
    private String picpath2 = "";
    private String picpath3 = "";
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2; //
    /**
     * 选择文件
     */
    public static final int TO_SELECT_PHOTO = 3;
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    /* 图片名称 */
    private static final String PHOTO_FILE_NAME = "/leave_photo.jpg";
    private LayoutInflater inflater;
    private ArrayList<LeavephotoBean> list = new ArrayList<>();
//    List<LeavephotoBean> list_leatphoto = new ArrayList<>();
    private File tempFile;
    private Bitmap bitmap;
    private String imagePath;
    private String requestURL = Contants.course_api + "/rest/upload/image";
    private String webServerUrl;
    private String leave_picpath1;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case UPLOAD_FILE_DONE:
                    dismissLoading();
                    String jsonStr = msg.obj.toString();
                    System.out.println("json===" + jsonStr);

                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");
                        if (result == 1) {
                            String data = json.getString("data");
                            JSONObject listObj = new JSONObject(data);
                            webServerUrl = listObj.getString("webServerUrl");
                            leave_picpath1 = listObj.getString("picpath1");
                            imagePaths.add(webServerUrl + leave_picpath1);
                            if (imagePaths.contains("paizhao")) {
                                imagePaths.remove("paizhao");
                                imagePaths.add("paizhao");
                            } else {
                                imagePaths.add("paizhao");
                            }
                            if (!TextUtils.isEmpty(leave_picpath1)) {
                                LeavephotoBean bean = new LeavephotoBean();
                                bean.setIcon(leave_picpath1);
                                list.add(bean);
                            }

                            if (null != imagePaths && imagePaths.size() != 0) {
                                gridAdapter = new GridLeaveAdapter(imagePaths);
                                gridView.setAdapter(gridAdapter);
                            }
                            System.out.println("list====" + list.toString());
                        } else {
                            showToast(reason);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_leave);

        init();

    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("请假");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.bt_submit_leave).setOnClickListener(this);
        //圆形选择框
        rg_leave = (RadioGroup) findViewById(R.id.rg_leave);
        rg_leave.setOnCheckedChangeListener(new LeaveRadioButtonListener());//给RadioGroup绑定监视器
        //开始时间
        tv_starttime = (TextView) findViewById(R.id.tv_starttime);
        findViewById(R.id.tv_starttime).setOnClickListener(this);
        //结束时间
        tv_endtime = (TextView) findViewById(R.id.tv_endtime);
        findViewById(R.id.tv_endtime).setOnClickListener(this);
        //请假原因
        et_reason = (EditText) findViewById(R.id.et_reason);
        inflater = LayoutInflater.from(this);
        gridView = (MyGridView) this.findViewById(R.id.gridView_leave);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//		mAdapter = new GridAdapter(this);
//		mAdapter.update();
//		gridView.setAdapter(mAdapter);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs)) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(LeaveActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
//					Toast.makeText(DynamicPublishActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(LeaveActivity.this);
                    intent.setCurrentItem(position);
                    //如果不加这行会导致选完图片以后在主界面点击图片预览会多出一张没有default_error 的图片
                    imagePaths.remove(imagePaths.size() - 1);

                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        imagePaths.add("paizhao");
        gridAdapter = new GridLeaveAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        initDatePicker();


    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_leave;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    class LeaveRadioButtonListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 选中状态改变时被触发
            switch (checkedId) {
                case R.id.rb_personal_leave:
                    // 当用户选择事假时
                    typeLeave = 0;
                    break;
                case R.id.rb_sick_leave:
                    // 当用户选择病假时
                    typeLeave = 1;
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_starttime://开始时间
                // 日期格式为yyyy-MM-dd HH:mm
                customDatePicker_startime.show(tv_starttime.getText().toString());
                break;
            case R.id.tv_endtime://结束时间
                customDatePicker_endtime.show(tv_starttime.getText().toString());
                break;
            case R.id.bt_submit_leave:
                //上传图片
//				uploadPhoto();
                Log.i(TAG, "onClick: imagePathsremove====" + imagePaths.toString());
//				三个图片路径
                if (list.size() != 0) {
                    if (list.size() == 1) {
                        picpath1 = list.get(0).getIcon();
                    } else if (list.size() == 2) {
                        picpath1 = list.get(0).getIcon();
                        picpath2 = list.get(1).getIcon();
                    } else if (list.size() == 3) {
                        picpath1 = list.get(0).getIcon();
                        picpath2 = list.get(1).getIcon();
                        picpath3 = list.get(2).getIcon();
                    }
                }
                //提交请假
                if (Utils.isBlank(et_reason.getText().toString())) {
                    Toast.makeText(LeaveActivity.this, "请填写请假原因", Toast.LENGTH_LONG).show();
                    showhintDialog("提示", "请填写请假原因");
                } else if (tv_endtime.getText().toString().equals(tv_starttime.getText().toString())) {
                    showhintDialog("提示", "请选择请假时间");
                } else {
                    showApplyleavetrue();
                }
                break;
            default:
                break;
        }
    }

    private void uploadPhoto() {
        Map<String, String> params = new HashMap<>();
        if (imagePaths.size() != 0) {
            if (imagePaths.size() == 1) {
                params.put("pic1", imagePaths.get(0));
            } else if (imagePaths.size() == 2) {
                params.put("pic1", imagePaths.get(0));
                params.put("pic2", imagePaths.get(1));
            } else if (imagePaths.size() == 3) {
                params.put("pic1", imagePaths.get(0));
                params.put("pic2", imagePaths.get(1));
                params.put("pic3", imagePaths.get(2));
            }
        }

        String url = Contants.course_api + "/rest/leave/upload";
        OkHttpUtils.post()//
                .url(url)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i(TAG, "onResponse: " + response);
                    }
                });
    }

    //提交
    private void submit() {
        showLoading("申请中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.leaveApply,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("getPageListJson==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            Log.i("yy", "data=======================>" + result);
                            if (result == 1) {
                                showToast("申请成功！");
                                Intent intent = new Intent();
                                setResult(3, intent);
                                finish();

                                String data = json.getString("data");

                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("提交失败，请重新申请！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                map.put("userName", GlobalData.getUsername(getApplicationContext()));
                map.put("beginTime", tv_starttime.getText().toString());
                map.put("endTime", tv_endtime.getText().toString());
                map.put("type", String.valueOf(typeLeave));
                map.put("reason", et_reason.getText().toString());
                map.put("pic1", picpath1);
                map.put("pic2", picpath2);
                map.put("pic3", picpath3);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        now = sdf.format(new Date());
//		tv_starttime.setText(now.split(" ")[0]);
        tv_starttime.setText(now);
        tv_endtime.setText(now);

        customDatePicker_startime = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_starttime.setText(time);
            }
//        }, "2011-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        }, "2011-01-01 00:00", "2100-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker_startime.showSpecificTime(true); // 显示时和分
        customDatePicker_startime.setIsLoop(true); // 允许循环滚动

        customDatePicker_endtime = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_endtime.setText(time);
                compare_date(tv_starttime.getText().toString(), time);
            }
//        }, "2011-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        }, "2011-01-01 00:00", "2100-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker_endtime.showSpecificTime(true); // 显示时和分
        customDatePicker_endtime.setIsLoop(true); // 允许循环滚动
    }

    public int compare_date(String starttime, String endtime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date start = df.parse(starttime);
            Date end = df.parse(endtime);
            if (start.getTime() > end.getTime()) {
//				Toast.makeText(LeaveActivity.this, "1" , Toast.LENGTH_SHORT).show();
                show();
//				System.out.println("start 在end前");
                return 1;
            } else if (start.getTime() < end.getTime()) {
//				System.out.println("start在end后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    private void show() {
        ibuilder = new CustomDialog.Builder(LeaveActivity.this);
        ibuilder.setTitle("提示");
        ibuilder.setMessage("开始时间不能大于结束时间");
//		ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.dismiss();
//			}
//		});

        ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tv_starttime.setText(now);
                tv_endtime.setText(now);
            }
        });

        Dialog dialog = ibuilder.create();
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
    }

    private void showApplyleavetrue() {
        ibuilder = new CustomDialog.Builder(LeaveActivity.this);
        ibuilder.setTitle("请假");
        ibuilder.setMessage("您觉得您真的有必要请假吗？");
        ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //如果有图片，进行图片上传的操作
                Log.i(TAG, "onClick: imagePaths====" + imagePaths.toString());
                submit();
            }
        });

        Dialog dialog = ibuilder.create();
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
    }

    public class GridLeaveAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridLeaveAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(LeaveActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.include_item_published_grida, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            Logger.withTag("yy").log("listurls ======" + listUrls.toString());
            if (path.equals("paizhao")) {
                holder.image.setImageResource(R.drawable.icon_addpic_unfocused);
                holder.image.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhotoPickerIntent intent = new PhotoPickerIntent(LeaveActivity.this);
                        intent.setSelectModel(SelectModel.MULTI);
                        intent.setShowCarema(true); // 是否显示拍照
                        intent.setMaxTotal(1); // 最多选择照片数量，默认为6
                        intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                        startActivityForResult(intent, REQUEST_CAMERA_CODE);
//						showPhoto();
                    }
                });
            } else {
                Glide.with(LeaveActivity.this)
//						.load(Contants.course_api + path)
                        .load(path)
                        .placeholder(R.drawable.default_error)
                        .error(R.drawable.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    private void showPhoto() {
        Builder = new PhotosDialog.Builder(LeaveActivity.this);
        dialog = Builder.create();
        View view = inflater.inflate(R.layout.dialog_photo, null);

        view.findViewById(R.id.image_take).setOnClickListener(this);
        view.findViewById(R.id.image_video).setOnClickListener(this);

        // 相册
        view.findViewById(R.id.image_video).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                PhotoPickerIntent intent = new PhotoPickerIntent(LeaveActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(3); // 最多选择照片数量，默认为6
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE);
//				Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
//				getImage.addCategory(Intent.CATEGORY_OPENABLE);
//				getImage.setType("image/*");
//				startActivityForResult(getImage, PHOTO_REQUEST_GALLERY);
            }
        });

        // 拍照
        view.findViewById(R.id.image_take).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    //指定照片保存路径（SD卡），PHOTO_FILE_NAME 为一个临时文件，每次拍照后这个图片都会被替换
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment
                                    .getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                }
                startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
            }
        });

        dialog.addContentView(view, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();       //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.9
        p.height = (int) (d.getHeight() * 0.5);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.d(TAG, "数量：" + list.size());
                    loadAdpater(list, false);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    boolean ispreview = true;
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    loadAdpater(ListExtra, ispreview);
                    break;

            }
        }
        /*if (requestCode == PHOTO_REQUEST_CAMERA) {
				try {
					String picture = PHOTO_FILE_NAME;
					toUploadFile(picture);
//			ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
//					ArrayList<String> list = new ArrayList<>();
//					Log.d(TAG, "数量：" + list.size());
//					list.add(picture);
//					loadAdpater(list);
				} catch (Exception e) {
					e.printStackTrace();
			}
		}*/
    }

    private void toUploadFile(String imagepath) {
        String fileKey = "pic";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

        System.out.println("temp_photo==" + Config.SDPATH_HEAD + "temp_photo.jpg");
        uploadUtil.uploadFile(imagepath, fileKey,
                requestURL, null);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.sendMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }


    private void loadAdpater(ArrayList<String> paths, boolean ispreview) {

        if (ispreview) {
            imagePaths.clear();
            imagePaths.addAll(paths);
            if (imagePaths.contains("paizhao")) {
                imagePaths.remove("paizhao");
                imagePaths.add("paizhao");
            } else {
                imagePaths.add("paizhao");
            }
            Log.i("yy", "loadAdpater: paths.size======" + paths.size());
            Log.i("yy", "loadAdpater: paths.size======" + paths.toString());
//			Log.i("yy", "loadAdpater: paths.get(2)===== "+ paths.get(2));
            gridAdapter = new GridLeaveAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);
            list.clear();
            for (int i = 0; i < paths.size(); i++) {
                String result = paths.get(i).toString().substring(webServerUrl.length());
                Log.i("yy", "resultleavephoto==" + result);
                LeavephotoBean bean = new LeavephotoBean();
                bean.setIcon(result);
                list.add(bean);
            }
        } else {
            if (imagePaths != null && imagePaths.size() > 0) {
                imagePaths.remove("paizhao");
            }
            if (paths.contains("paizhao")) {
                paths.remove("paizhao");
            }
            if (imagePaths.size() > 2) {
                showToast("请假最多选择三张图片！");
                imagePaths.add("paizhao");
            } else {
                //上传图片
                showLoading("加载中...");
                String imagepath = ImageUtil.compressImage(paths.get(0), Config.SDPATH_HEAD + "temp_photo.jpg", 30);
                toUploadFile(imagepath);
            }
        }

//		if (paths.size() != 0) {
//			if (paths.size() == 1) {
//				picpath1 = paths.get(0);
//				Log.i("yy", "loadAdpater: picpath1===" + paths.get(0));
//			} else if (paths.size() == 2) {
//				picpath1 = paths.get(0);
//				picpath2 = paths.get(1);
//				Log.i("yy", "loadAdpater: picpath1===" + paths.get(0));
//				Log.i("yy", "loadAdpater: picpath2===" + paths.get(1));
//			} else if (paths.size() == 3) {
//				picpath1 = paths.get(0);
//				picpath2 = paths.get(1);
//				picpath3 = paths.get(2);
//				Log.i("yy", "loadAdpater: picpath1===" + paths.get(0));
//				Log.i("yy", "loadAdpater: picpath2===" + paths.get(1));
//				Log.i("yy", "loadAdpater: picpath3===" + paths.get(2));
//			}
//		}
//		picpath1 = paths.get(0);
//		picpath2 = paths.get(1);
//		picpath3 = paths.get(2);
//		if (imagePaths.size() <= 4) {
        gridAdapter = new GridLeaveAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
//		}else {
//			showToast("请假图片最多放三张！");
//		}
        try {
            JSONArray obj = new JSONArray(imagePaths);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
